<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS单例模式"><meta name="keywords" content="iOS"><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS单例模式 | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.</span> <span class="toc-text">单例模式</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%AE%80%E8%A6%81%E6%AD%A5%E9%AA%A4"><span class="toc-number">1.0.1.</span> <span class="toc-text">简要步骤</span></a></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS单例模式</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2016-03-12</time></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h3 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h3><p><strong>单例模式（Singleton）作用</strong>：</p>
<ul>
<li>可以保证的程序运行过程，一个类只有一个示例,并提供一个访问它的全局访问点方便外界访问</li>
<li>控制了实例个数，并节约系统资源。</li>
</ul>
<p>​    单例写法有好几种，通常的写法是基于线程安全的写法，保证单例对象只会被创建一次，为单例对象创建一个静态实例，可以写成全局的，也可以在类方法中实现，并置为nil。</p>
<h5 id="简要步骤"><a href="#简要步骤" class="headerlink" title="简要步骤"></a>简要步骤</h5><ul>
<li>1、先定义一个静态的instance.</li>
<li>2、定一个sharedInstance的类方法.能够被全局调用的.此方法里需要考虑线程安全问题</li>
<li>3、如果需要copy,需要遵守NSCopying协议,以及在copyWithZone中,直接返回self;</li>
</ul>
<p>创建一个继承继承自NSObject的类AccountManager</p>
<p><code>AccountManager.h</code>文件</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  AccountManager.h</span></span><br><span class="line"><span class="comment">//  Copyright © 2018年 hl.com.cn. All rights reserved.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#import <span class="string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">AccountManager</span> : <span class="title">NSObject</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**快速创建单例的类方法*/</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>

<p><code>AccountManager.m</code>文件（简洁版，不考虑<code>alloc</code>,<code>copy</code>方式创建单例）</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  AccountManager.m</span></span><br><span class="line"><span class="comment">//  Copyright © 2018年 hl.com.cn. All rights reserved.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#import <span class="string">&quot;AccountManager.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">AccountManager</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">//为单例对象创建的静态实例，因为对象的唯一性，必须是static类型</span></span><br><span class="line"><span class="keyword">static</span> AccountManager *_sharedInstance = <span class="literal">nil</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">pragma</span> mark---创建单例(普通，同步锁，GCD三种方式)</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 最简单的单例(不建议使用)</span></span><br><span class="line"><span class="comment"> * 缺点：没有考虑多线程并发问题（非线程安全）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance1&#123;</span><br><span class="line">    <span class="keyword">if</span> (!_sharedInstance) &#123;</span><br><span class="line">        _sharedInstance = [[<span class="keyword">self</span> alloc]init];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *同步锁版本</span></span><br><span class="line"><span class="comment"> *优点：线程安全</span></span><br><span class="line"><span class="comment"> *缺点：每次运行代码前都要获取锁，效率较GCD慢</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance&#123;</span><br><span class="line">    <span class="comment">//考虑多线程并发问题, 所以加个@synchronized同步锁</span></span><br><span class="line">    <span class="keyword">@synchronized</span>(<span class="keyword">self</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!_sharedInstance) &#123;</span><br><span class="line">            _sharedInstance = [[<span class="keyword">self</span> alloc] init];</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *GCD版本（线程安全）--🍎推荐</span></span><br><span class="line"><span class="comment"> *优点：1、线程安全 2、无需担心加锁或同步</span></span><br><span class="line"><span class="comment"> *缺点：暂无</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="built_in">dispatch_once_t</span> onceToken;<span class="comment">/*这个拿到函数体外,成为全局的,用于访问销毁单例*/</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance2 &#123;</span><br><span class="line">    <span class="comment">//dispatch_once保证线程安全</span></span><br><span class="line">    <span class="built_in">dispatch_once</span>(&amp;onceToken, ^&#123;</span><br><span class="line">        _sharedInstance = [[<span class="keyword">self</span> alloc] init];</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">pragma</span> mark---销毁单例</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 同步锁版本:销毁单例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+(<span class="type">void</span>)attemptDealloc&#123;</span><br><span class="line">    _sharedInstance = <span class="literal">nil</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * GCD版本:销毁单例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+(<span class="type">void</span>)attempDealloc&#123;</span><br><span class="line">     onceToken = <span class="number">0</span>; <span class="comment">// 只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.</span></span><br><span class="line">    _sharedInstance = <span class="literal">nil</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样就是一个完整的单例,保证怎么创建都是唯一的.</p>
<p>测试单例</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)viewDidLoad &#123;</span><br><span class="line">    [<span class="variable language_">super</span> viewDidLoad];</span><br><span class="line">    <span class="comment">// Do any additional setup after loading the view, typically from a nib.</span></span><br><span class="line">    AccountManager *obj1 = [AccountManager sharedInstance] ;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;obj1 = %@&quot;</span>, obj1) ;</span><br><span class="line"></span><br><span class="line">    AccountManager *obj2 = [AccountManager sharedInstance] ;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;obj2 = %@&quot;</span>, obj2) ;</span><br><span class="line"></span><br><span class="line">    AccountManager *obj3 = [[AccountManager alloc] init] ;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;obj3 = %@&quot;</span>, obj3) ;</span><br><span class="line"></span><br><span class="line">    AccountManager* obj4 = [[AccountManager alloc] init] ;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;obj4 = %@&quot;</span>, [obj4 <span class="keyword">copy</span>]) ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>打印详情</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">2016-03-12 14:30:52.078030+0800 SingletonDemo[3438:763080] obj1 = &lt;AccountManager: 0x60400001dfb0&gt;</span><br><span class="line">2016-03-12 14:30:52.078208+0800 SingletonDemo[3438:763080] obj2 = &lt;AccountManager: 0x60400001dfb0&gt;</span><br><span class="line">2016-03-12 14:30:52.078340+0800 SingletonDemo[3438:763080] obj3 = &lt;AccountManager: 0x60000001e230&gt;</span><br><span class="line">2016-03-12 14:30:52.078340+0800 SingletonDemo[3438:763080] obj4 直接Crash</span><br></pre></td></tr></table></figure>

<p>​	以上创建单例方式基本可以了，通过<code>alloc</code>，<code>copy</code>方式创建单例本身就是一种非规范写法，但为了提高容错率，我们还是处理下<code>alloc</code>，<code>copy</code>方式创建单例。</p>
<p>升级版</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  AccountManager.m</span></span><br><span class="line"><span class="comment">//  Copyright © 2018年 hl.com.cn. All rights reserved.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#import <span class="string">&quot;AccountManager.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">AccountManager</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">//为单例对象创建的静态实例，因为对象的唯一性，必须是static类型</span></span><br><span class="line"><span class="keyword">static</span> AccountManager *_sharedInstance = <span class="literal">nil</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 最简单的单例</span></span><br><span class="line"><span class="comment"> * 缺点：没有考虑多线程并发问题（非线程安全）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance1&#123;</span><br><span class="line">    <span class="keyword">if</span> (!_sharedInstance) &#123;</span><br><span class="line">        _sharedInstance = [[<span class="keyword">self</span> alloc]init];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *同步锁版本</span></span><br><span class="line"><span class="comment"> *优点：线程安全</span></span><br><span class="line"><span class="comment"> *缺点：每次运行代码前都要获取锁，效率较GCD慢</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance&#123;</span><br><span class="line">    <span class="comment">//考虑多线程并发问题, 所以加个@synchronized同步锁</span></span><br><span class="line">    <span class="keyword">@synchronized</span>(<span class="keyword">self</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!_sharedInstance) &#123;</span><br><span class="line">            _sharedInstance = [[<span class="variable language_">super</span> allocWithZone:<span class="literal">NULL</span>] init];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *GCD版本（线程安全）--🍎推荐</span></span><br><span class="line"><span class="comment"> *优点：1、线程安全 2、无需担心加锁或同步</span></span><br><span class="line"><span class="comment"> *缺点：暂无</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="built_in">dispatch_once_t</span> onceToken;<span class="comment">/*这个拿到函数体外,成为全局的,用于访问销毁单例*/</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance2 &#123;</span><br><span class="line">    <span class="comment">//dispatch_once保证线程安全</span></span><br><span class="line">    <span class="built_in">dispatch_once</span>(&amp;onceToken, ^&#123;</span><br><span class="line">        _sharedInstance = [[<span class="keyword">self</span> alloc] init];</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> _sharedInstance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">pragma</span> mark---销毁单例</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> 同步锁版本:销毁单例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+(<span class="type">void</span>)attemptDealloc1&#123;</span><br><span class="line">    _sharedInstance = <span class="literal">nil</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> GCD版本:销毁单例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+(<span class="type">void</span>)attempDealloc2&#123;</span><br><span class="line">     onceToken = <span class="number">0</span>; <span class="comment">// 只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.</span></span><br><span class="line">    _sharedInstance = <span class="literal">nil</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">pragma</span> mark---完善alloc，copy方式创建的单例</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *创建对象的步骤分为申请内存(alloc)-&gt;初始化(init)这两个步骤，我们要确保对象的唯一性，因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时，OC内部会调用allocWithZone这个方法来申请内存，我们重写这个方法，然后在这个方法中调用shareInstance方法返回单例对象，这样就可以达到我们的目的。拷贝对象也是同样的原理，重写copyWithZone方法，然后在这个方法中调用shareInstance方法返回单例对象。</span></span><br><span class="line"><span class="comment"> * 重写allocWithZone方法，保证alloc或者init创建的实例不会产生新实例，因为该类覆盖了allocWithZone方法，所以只能通过其父类分配内存，即[super allocWithZone]</span></span><br><span class="line"><span class="comment"> *    AccountManager *account= [AccountManager alloc]init];</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)allocWithZone:(<span class="keyword">struct</span> _NSZone *)zone &#123;</span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> sharedInstance];<span class="comment">// 直接调用单例的创建方法</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  NSCopying协议,重写copyWithZone方法，保证copy不会产生新实例，</span></span><br><span class="line"><span class="comment"> *   保证copy时相同 防止AccountManager *account= [AccountManager copy];方式出现Crash</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="type">id</span>)copyWithZone:(<span class="keyword">struct</span> _NSZone *)zone &#123;</span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> sharedInstance];</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 重写copy方法</span></span><br><span class="line">- (<span class="type">id</span>)<span class="keyword">copy</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重写 mutableCopy 方法</span></span><br><span class="line">- (<span class="type">id</span>)mutableCopy &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>

<p>测试打印信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">2016-03-12 14:53:17.572240+0800 SingletonDemo[3995:849854] obj1 = &lt;AccountManager: 0x600000007850&gt;</span><br><span class="line">2016-03-12 14:53:17.572624+0800 SingletonDemo[3995:849854] obj2 = &lt;AccountManager: 0x600000007850&gt;</span><br><span class="line">2016-03-12 14:53:17.572768+0800 SingletonDemo[3995:849854] obj3 = &lt;AccountManager: 0x600000007850&gt;</span><br><span class="line">2016-03-12 14:53:17.572909+0800 SingletonDemo[3995:849854] obj4 = &lt;AccountManager: 0x600000007850&gt;</span><br></pre></td></tr></table></figure>

</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2016/03/12/单例写法 /">http://huluo666.gitee.io/2016/03/12/单例写法 /</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/iOS/">iOS</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2016/03/15/Swift%E5%AD%A6%E4%B9%A0-UITableView%E7%9A%84%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/"><i class="fa fa-chevron-left">  </i><span>Swift学习-UITableView的简单使用</span></a></div><div class="next-post pull-right"><a href="/2016/03/09/Runtime%E4%B9%8B%E6%96%B9%E6%B3%95%E4%BA%A4%E6%8D%A2/"><span>runtime之方法交换</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>